import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _isNil from "lodash/isNil";
import { getResponse, createPagination } from 'utils/utils';
import { queryIdpValue } from 'cpaas-front/lib/services/api';
import { fetchOrgInfo as _fetchOrgInfo, saveEdit, forbindLine, enabledLine as _enabledLine, saveAdd, organizationQueryLazyTree, organizationQueryLine } from "../services/organizationService";

function buildNewTreeDataSource() {
  var treeDataSource = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var iterFunc = arguments.length > 1 ? arguments[1] : undefined;
  return treeDataSource.map(function (item) {
    if (item.children) {
      var newItem = iterFunc(item);
      return _objectSpread(_objectSpread({}, newItem), {}, {
        children: buildNewTreeDataSource(newItem.children, iterFunc)
      });
    } else {
      return iterFunc(item);
    }
  });
}

function transformData() {
  var dataSource = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var indent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  return dataSource.map(function (item) {
    if (item.hasNextFlag === 1) {
      return _objectSpread(_objectSpread({}, item), {}, {
        indent: indent,
        children: []
      });
    } else {
      return _objectSpread(_objectSpread({}, item), {}, {
        indent: indent
      });
    }
  });
}

export default {
  namespace: 'organization',
  state: {
    groupCode: '',
    groupName: '',
    unitType: [],
    treeDataSource: [],
    // 树结构数据
    expandKeys: [],
    // 树结构数据展开的数据
    loadingExpandKeys: [],
    // 加载数据中的行
    lineDataSource: [],
    // 打平分页的数据
    linePagination: {} // 打平分页

  },
  effects: {
    // 获取组织信息
    fetchOrgInfo: /*#__PURE__*/_regeneratorRuntime.mark(function fetchOrgInfo(_, _ref) {
      var call, put, organization, unitType;
      return _regeneratorRuntime.wrap(function fetchOrgInfo$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              call = _ref.call, put = _ref.put;
              _context.t0 = getResponse;
              _context.next = 4;
              return call(_fetchOrgInfo);

            case 4:
              _context.t1 = _context.sent;
              organization = (0, _context.t0)(_context.t1);
              _context.next = 8;
              return call(queryIdpValue, 'CPFM.HR.UNIT_TYPE');

            case 8:
              unitType = _context.sent;

              if (!organization) {
                _context.next = 12;
                break;
              }

              _context.next = 12;
              return put({
                type: 'updateState',
                payload: {
                  groupCode: organization.tenantNum,
                  groupName: organization.tenantName,
                  // TODO: 这里为什么要过滤 这个 D
                  unitType: unitType.filter(function (item) {
                    return item.value !== 'D';
                  })
                }
              });

            case 12:
            case "end":
              return _context.stop();
          }
        }
      }, fetchOrgInfo);
    }),
    // // 获取组织数据（树形展示）
    // * searchOrganizationData({payload}, {call, put}) {
    //   const {tenantId, unitName, unitCode, expandFlag, expandedRowKeys, ...others} = payload;
    //   let result = {};
    //   let expandedRow = {};
    //   if (unitCode || unitName) {
    //     result = yield call(search, {tenantId, unitName, unitCode});
    //   } else {
    //     result = yield call(searchAll, {tenantId});
    //   }
    //   result = getResponse(result);
    //   const {renderTree, pathMap} = renderTreeData(result, {});
    //   if (!expandFlag) {
    //     expandedRow = {
    //       expandedRowKeys: Object.keys(pathMap).map(item => +item),
    //     };
    //   } else {
    //     const unitIdList = result.map(item => item.unitId) || [];
    //     expandedRow = {
    //       expandedRowKeys: Array.from(
    //         new Set([...expandedRowKeys, ...unitIdList])),
    //     };
    //   }
    //   yield put({
    //     type: 'updateState',
    //     payload: {
    //       renderTree,
    //       pathMap,
    //       addData: {},
    //       ...expandedRow,
    //       ...others,
    //     },
    //   });
    // },
    // 更新组织信息
    saveEditData: /*#__PURE__*/_regeneratorRuntime.mark(function saveEditData(_ref2, _ref3) {
      var payload, call, result;
      return _regeneratorRuntime.wrap(function saveEditData$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              payload = _ref2.payload;
              call = _ref3.call;
              _context2.next = 4;
              return call(saveEdit, payload);

            case 4:
              result = _context2.sent;
              return _context2.abrupt("return", getResponse(result));

            case 6:
            case "end":
              return _context2.stop();
          }
        }
      }, saveEditData);
    }),
    // 新增组织信息
    saveAddData: /*#__PURE__*/_regeneratorRuntime.mark(function saveAddData(_ref4, _ref5) {
      var payload, call, result;
      return _regeneratorRuntime.wrap(function saveAddData$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              payload = _ref4.payload;
              call = _ref5.call;
              _context3.next = 4;
              return call(saveAdd, payload);

            case 4:
              result = _context3.sent;
              return _context3.abrupt("return", getResponse(result));

            case 6:
            case "end":
              return _context3.stop();
          }
        }
      }, saveAddData);
    }),
    // 禁用“组织行”
    forbidLine: /*#__PURE__*/_regeneratorRuntime.mark(function forbidLine(_ref6, _ref7) {
      var payload, call, result;
      return _regeneratorRuntime.wrap(function forbidLine$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              payload = _ref6.payload;
              call = _ref7.call;
              _context4.next = 4;
              return call(forbindLine, payload);

            case 4:
              result = _context4.sent;
              return _context4.abrupt("return", getResponse(result));

            case 6:
            case "end":
              return _context4.stop();
          }
        }
      }, forbidLine);
    }),
    // 启用“组织行”
    enabledLine: /*#__PURE__*/_regeneratorRuntime.mark(function enabledLine(_ref8, _ref9) {
      var payload, call, result;
      return _regeneratorRuntime.wrap(function enabledLine$(_context5) {
        while (1) {
          switch (_context5.prev = _context5.next) {
            case 0:
              payload = _ref8.payload;
              call = _ref9.call;
              _context5.next = 4;
              return call(_enabledLine, payload);

            case 4:
              result = _context5.sent;
              return _context5.abrupt("return", getResponse(result));

            case 6:
            case "end":
              return _context5.stop();
          }
        }
      }, enabledLine);
    }),
    unitsQueryLazyTree: /*#__PURE__*/_regeneratorRuntime.mark(function unitsQueryLazyTree(_ref10, _ref11) {
      var _ref10$payload, payload, call, put, unitId, _payload$indent, indent, params, queryChild, res, responseRes;

      return _regeneratorRuntime.wrap(function unitsQueryLazyTree$(_context6) {
        while (1) {
          switch (_context6.prev = _context6.next) {
            case 0:
              _ref10$payload = _ref10.payload, payload = _ref10$payload === void 0 ? {} : _ref10$payload;
              call = _ref11.call, put = _ref11.put;
              unitId = payload.unitId, _payload$indent = payload.indent, indent = _payload$indent === void 0 ? -1 : _payload$indent;
              params = {};
              queryChild = !_isNil(unitId);

              if (queryChild) {
                params.unitId = unitId;
              }

              _context6.next = 8;
              return put({
                type: 'updateLoadingExpandKeys',
                payload: {
                  queryChild: queryChild,
                  unitId: unitId,
                  type: 'load'
                }
              });

            case 8:
              _context6.next = 10;
              return call(organizationQueryLazyTree, params);

            case 10:
              res = _context6.sent;
              responseRes = getResponse(res);

              if (!responseRes) {
                _context6.next = 15;
                break;
              }

              _context6.next = 15;
              return put({
                type: 'updateTreeDataSource',
                payload: {
                  queryChild: queryChild,
                  unitId: unitId,
                  treeData: transformData(responseRes, indent + 1)
                }
              });

            case 15:
              _context6.next = 17;
              return put({
                type: 'updateLoadingExpandKeys',
                payload: {
                  queryChild: queryChild,
                  unitId: unitId,
                  type: 'unload'
                }
              });

            case 17:
            case "end":
              return _context6.stop();
          }
        }
      }, unitsQueryLazyTree);
    }),
    unitsQueryLine: /*#__PURE__*/_regeneratorRuntime.mark(function unitsQueryLine(_ref12, _ref13) {
      var payload, call, put, params, res, responseRes;
      return _regeneratorRuntime.wrap(function unitsQueryLine$(_context7) {
        while (1) {
          switch (_context7.prev = _context7.next) {
            case 0:
              payload = _ref12.payload;
              call = _ref13.call, put = _ref13.put;
              params = payload.params;
              _context7.next = 5;
              return call(organizationQueryLine, params);

            case 5:
              res = _context7.sent;
              responseRes = getResponse(res);

              if (!responseRes) {
                _context7.next = 10;
                break;
              }

              _context7.next = 10;
              return put({
                type: 'updateState',
                payload: {
                  lineDataSource: responseRes.content,
                  linePagination: createPagination(responseRes)
                }
              });

            case 10:
            case "end":
              return _context7.stop();
          }
        }
      }, unitsQueryLine);
    })
  },
  reducers: {
    updateState: function updateState(state, _ref14) {
      var payload = _ref14.payload;
      return _objectSpread(_objectSpread({}, state), payload);
    },
    // 由于 可能异步问题 导致 数据不一致, 所以更新放到 reducer 中
    updateTreeDataSource: function updateTreeDataSource(state, _ref15) {
      var payload = _ref15.payload;
      var queryChild = payload.queryChild,
          unitId = payload.unitId,
          treeData = payload.treeData;
      return _objectSpread(_objectSpread({}, state), {}, {
        treeDataSource: queryChild ? buildNewTreeDataSource(state.treeDataSource, function (item) {
          if (item.unitId === unitId) {
            return _objectSpread(_objectSpread({}, item), {}, {
              children: treeData
            });
          } else {
            return item;
          }
        }) : treeData,
        expandKeys: queryChild ? [].concat(_toConsumableArray(state.expandKeys), [unitId]) : []
      });
    },
    // 由于 expand 问题, expand 由自己管理
    updateLoadingExpandKeys: function updateLoadingExpandKeys(state, _ref16) {
      var payload = _ref16.payload;
      var queryChild = payload.queryChild,
          unitId = payload.unitId,
          type = payload.type;

      if (!queryChild) {
        return _objectSpread(_objectSpread({}, state), {}, {
          loadingExpandKeys: []
        });
      }

      switch (type) {
        case 'load':
          return _objectSpread(_objectSpread({}, state), {}, {
            loadingExpandKeys: [].concat(_toConsumableArray(state.loadingExpandKeys), [unitId])
          });

        case 'unload':
          return _objectSpread(_objectSpread({}, state), {}, {
            loadingExpandKeys: state.loadingExpandKeys.filter(function (k) {
              return k !== unitId;
            })
          });

        default:
          return state;
      }
    }
  }
};